package cn.kgc.service;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;

/**
 * @author YC
 */
@Service
public class WxPayService {

    @Autowired
    private HttpClient httpClient;

    @Value("${wechat.pay.appid}")
    private String appid;

    @Value("${wechat.pay.mch-id}")
    private String mchId;

    @Value("${wechat.pay.notify-url}")
    private String notifyUrl;

    /**
     * 向微信支付系统发送统一下单请求
     */
    public String createNativeOrder(String orderId, int amount, String description) throws Exception {
        //向微信支付系统地址发送post请求
        HttpPost request = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native ");
        //在请求头中设置json格式的数据
        request.setHeader("Content-Type", "application/json");
        // 构建请求体(发送请求的内容)
        JSONObject body = new JSONObject();
        //商户id
        body.put("mchid", mchId);
        //应用id
        body.put("appid", appid);
        //商品描述
        body.put("description", description);
        //订单号
        body.put("out_trade_no", orderId);
        //回调地址(微信支付系统通过此地址给商户系统发送通知)
        body.put("notify_url", notifyUrl);
        //金额单位是分
        body.put("amount", new JSONObject().put("total", amount));
        //请求体设置请求内容
        request.setEntity(new StringEntity(body.toString()));
        // 发送请求
        HttpResponse response = httpClient.execute(request);
        // 获取响应体
        String responseBody = EntityUtils.toString(response.getEntity());
        // 将响应体转换为json对象
        JSONObject jsonObject = new JSONObject(responseBody);
        //从响应体中获得二维码的连接 返回二维码链接
        return jsonObject.getString("code_url");
    }

}